package hcd.mynote;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class EditFragment extends Fragment {

    private EditText titleEditText;
    private EditText contentEditText;
    private OnEditBackListener editBackListener;
    private Note editNote;
    private boolean saving = false;
    private boolean saveFailed = false;
    private LitepalSaveHandler saveHandler = new LitepalSaveHandler();

    private String loginUsername;

    public EditFragment() {
        // Required empty public constructor
    }

//    @Override
//    public void setArguments(Bundle args) {
//        super.setArguments(args);
//    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getActivity().setTitle("编辑笔记");
        setHasOptionsMenu(true);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_edit, container, false);
        titleEditText = (EditText) view.findViewById(R.id.title_edit);
        contentEditText = (EditText) view.findViewById(R.id.content_edit);
        try {
//            editNote = (Note) getArguments().get("note");
            editNote = (Note) getArguments().getSerializable("note");
//            titleEditText.setText(getArguments().getString(getString"title"));
//            contentEditText.setText(getArguments().getString("content"));
        }catch (Exception e){
            e.printStackTrace();
        }
        if (editNote == null) editNote = new Note("", "", System.currentTimeMillis());
        titleEditText.requestFocus();

        try{
            loginUsername = getArguments().getString("user");
            Log.d("EditFragment: ", "loginUsername: "+loginUsername);
        }catch (Exception ignore){}

        titleEditText.setText(editNote.getTitle());
        contentEditText.setText(editNote.getContent());


        return view;
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
//        menu.findItem(R.id.action_save).setEnabled(canSave());
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
//                ((HomeActivity) getActivity()).setCurrentFragment(HomeActivity.HOME_FRAGMENT);
                getActivity().getSupportFragmentManager().popBackStack();
                return true;
            case R.id.action_save:

                saveNote(0);
//                ((HomeActivity) getActivity()).setCurrentFragment(HomeActivity.HOME_FRAGMENT);
//                getActivity().getSupportFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();

//        titleEditText.clearFocus();
//        contentEditText.clearFocus();
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(titleEditText.getWindowToken(), 0);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(contentEditText.getWindowToken(), 0);

        try{
            // 退出自动保存
            if (canSave()) saveNote(0);

            // 显示主页的导航栏的内容
            getActivity().setTitle("我的笔记");
            ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);

            // 返回事件调用
            editBackListener.back();

            // 更改当前为主页
            ((HomeActivity) getActivity()).setCurrentFragment(HomeActivity.HOME_FRAGMENT);

            // 更新导航栏
            getActivity().getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void setEditBackListener(OnEditBackListener editBackListener) {
        this.editBackListener = editBackListener;
    }

    public OnEditBackListener getEditBackListener() {
        return editBackListener;
    }

    private boolean canSave(){
        if (saveFailed) return true;

        if (titleEditText.getText().toString().equals(editNote.getTitle()) && contentEditText.getText().toString().equals(editNote.getContent())) {
            return false;
        }

        if (saving) return false;

        return true;
    }

    private void saveNote(final int flag){
        if (!canSave()) return;
        saving = true;
        saveFailed = false;


        (new Thread(){
            @Override
            public void run() {
                try {
                    editNote.setTitle(titleEditText.getText().toString());
                    editNote.setContent(contentEditText.getText().toString());
                    editNote.setTime(System.currentTimeMillis());
                    editNote.save();
                }catch (Exception e){
                    e.printStackTrace();
                    saving = false;
                    saveFailed = true;
                    saveHandler.obtainMessage(-1, flag).sendToTarget();
                    return;
                }
                // 云端
                try{
                    saving = false;
                    if (loginUsername == null || loginUsername.isEmpty()){
                        throw new Exception("not_login");
                    }
                    Bmob.saveNote(editNote, loginUsername);
                    saveHandler.obtainMessage(0, flag).sendToTarget();
                }catch (Exception e){
                    e.printStackTrace();
                    saveHandler.obtainMessage(1, flag).sendToTarget();
                }

            }
        }).start();
    }

    private class LitepalSaveHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String time = "";
            if ((int) msg.obj == 1){
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
                time = sdf.format(new Date());
            }
            try{
                if (msg.what == 0) {
                    Toast.makeText(getContext(), time+"已保存", Toast.LENGTH_SHORT).show();
                }else if (msg.what == 1){
                    Toast.makeText(getContext(), "保存到云端失败, 已存本地", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getContext(), time+"保存失败", Toast.LENGTH_SHORT).show();
                }
            }catch (Exception ignore){

            }


        }
    }
}
